package middleware

import (
	"github.com/gin-gonic/gin"
	"naio/config"
	"naio/errs"
	"naio/pkg/casbin"
	"naio/pkg/jwt"
	"net/http"
)

//TODO 检查管理员权限中间件
func CheckPermission() gin.HandlerFunc {
	return func(c *gin.Context) {
		if config.Config.Env == "dev" {
			// dev模式下放行
			c.Next()
		}else{
			// 根据上下文获取载荷claims, 从claims获取role名称
			claims := c.MustGet("claims").(*jwt.Payload)
			//获取用户的角色名称
			role := claims.Role
			e := casbin.Setup()
			//获取请求的URI
			obj := c.Request.URL.RequestURI()
			//获取请求方法
			act := c.Request.Method
			// 判断策略中是否存在
			res, err := e.Enforce(role, obj, act)
			if err != nil {
				panic(errs.NewMyAPIError(errs.ErrorAuthAction, err.Error()))
			}
			if res {
				c.Next()
			}else{
				c.JSON(http.StatusOK, gin.H{
					"request_url": c.Request.URL.String(),
					"code": 10008,
					"msg": "对不起,您没有权限访问此接口",
					"data": nil,
				})
				c.Abort()
				return
				//panic(errs.NewMyAPIError(errs.ErrorAuthAction, "抱歉,您没有此权限!"))
			}
		}
	}
}
